package com.example.maxboxtwo.utils;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.widget.Toast;

import com.example.maxboxtwo.utils.listeners.interfaces.ExecuteInBackListener;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

/**
 * @Void :params be used to putting into CLass
 * @Integer: represent progress of project
 * @Boolea: the result of the execution
 */
public class ExecuteInBack extends AsyncTask <Location,String,Address>{
    private ExecuteInBackListener listener;
    private Context context;

    public ExecuteInBack(ExecuteInBackListener listener,Context context) {
        this.listener = listener;
        this.context = context;
        Toast.makeText(context,"constructor",Toast.LENGTH_LONG).show();    }

    /**
    * the function will do some things before executing operation
    */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    //the function will do some things about logical deal
    @Override
    protected Address doInBackground(Location... objects) {
        Toast.makeText(context,"dfsf",Toast.LENGTH_LONG).show();
        Geocoder geocoder = new Geocoder(context, Locale.getDefault());
        if(geocoder.isPresent()){
            try {
                Toast.makeText(context,"45",Toast.LENGTH_LONG).show();
                List<Address>addresses =  geocoder.getFromLocation(objects[0].getLatitude(),objects[0].getLongitude(),1);
                return addresses.get(0);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            publishProgress("you device don't support the function");
        }

        return null;
    }

    /**
     * @param values
     * the values represent progress of project
     */
    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        listener.dialog(values[0]);
    }

    /**
     * @param address
     * when the operation is finished,executing some post-treatment
     */
    @Override
    protected void onPostExecute(Address address) {
        super.onPostExecute(address);
        listener.showAddress(address);

    }
}
